package org.musicsweet.service;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.musicsweet.constant.StringConstant;
import org.musicsweet.entity.SysUser;
import org.musicsweet.mapper.SysUserMapper;
import org.musicsweet.result.ResultData;
import org.musicsweet.util.RedisUtil;
import org.musicsweet.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 系统用户Service
 */
@Slf4j
@Service
public class SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RedisUtil redisUtil;


    /**
     * 根据id查询系统用户
     *
     * @param sysUser
     * @return
     */
    public ResultData<SysUser> getUserById(SysUser sysUser) {
        log.info("根据id查询系统用户:"+ JSON.toJSONString(sysUser));
        if(StringUtils.isEmpty(sysUser.getId())){
            return ResultData.createFail("id不能为空");
        }
        sysUser.setDel(StringConstant.DEL_NO);
        SysUser userObj = sysUserMapper.getUserById(sysUser);
        return ResultData.successData("查询成功",userObj);
    }

    /**
     * 多条件查询系统用户
     *
     * @param sysUser
     * @return
     */
    public ResultData<List<SysUser>> getUserList(SysUser sysUser) {
        log.info("多条件查询系统用户:"+ JSON.toJSONString(sysUser));
        sysUser.setDel(StringConstant.DEL_NO);
        List<SysUser> sysUsers = sysUserMapper.getUserList(sysUser);
        return ResultData.successData("查询成功",sysUsers);
    }


    /**
     * 添加系统用户
     * MultipartFile上传文件用的   在后台是key  前台会有一个FormData的方法 key和value键值对的方式储存对象
     * @param sysUser
     * @return
     */
    @Transactional
    public ResultData addSysUser(SysUser sysUser, MultipartFile file, String token) {
        if(StringUtils.isEmpty(sysUser.getUsername())){
            return ResultData.createFail("用户名不能为空");
        }
        if(StringUtils.isEmpty(sysUser.getPassword())){
            return ResultData.createFail("密码不能为空");
        }
        if(StringUtils.isEmpty(sysUser.getNickName())){
            return ResultData.createFail("昵称不能为空");
        }
        if(StringUtils.isEmpty(sysUser.getRoleId())){
            return ResultData.createFail("所属角色不能为空");
        }
        if(file == null){
            return ResultData.createFail("头像不能为空");
        }
        //定义一个临时的对象,用来查询用户名是否存在
        SysUser nameUser = new SysUser();
        //将输入的值塞进去之后进行getUserList查询
        nameUser.setUsername(sysUser.getUsername());
        List<SysUser> nameUserList = sysUserMapper.getUserList(nameUser);
        //如果不为空说明用户名已存在
        if(!CollectionUtils.isEmpty(nameUserList)){
            return ResultData.createFail("用户名已存在,请重新输入");
        }

        //头像的上传   首先先创建一个新路径
        File uploadFile = new File(StringConstant.UPLOAD_ROOT_PATH);
        //因为防止图片名重名的而找不到  所以使用uuid的方式进行数据的拼接
        String fileName = StringUtil.getUUID()+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String filePath = StringConstant.UPLOAD_ROOT_PATH+"\\"+fileName;
        //如果头像的路径在本地是否存在  如果不存在
        if(!uploadFile.exists()){
            //mkdirs()是创建多级目录
            uploadFile.mkdirs();
        }
        try {
            //transferto()方法，是springmvc封装的方法，用于图片上传时，把内存中图片写入磁盘
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        sysUser.setHeadImg(fileName);
        sysUser.setId(StringUtil.getUUID());
        sysUser.setCreateTime(new Date());
        //token对应着用户的信息
        SysUser curSysUser = getSysUserByToken(token).getData();
        //上传者的信息可以通过token获取到
        sysUser.setCreateUserId(curSysUser.getId());
        sysUser.setDel(StringConstant.DEL_NO);
        log.info("添加系统用户:"+ JSON.toJSONString(sysUser));
        int i = sysUserMapper.addSysUser(sysUser);
        if(i>0){
            return ResultData.createSuccess("添加成功");
        }else{
            return ResultData.createFail("添加系统用户失败");
        }
    }


    /**
     * 修改系统用户
     *
     * @param sysUser
     * @return
     */
    @Transactional
    public ResultData updateSysUser(SysUser sysUser,MultipartFile file,String token) {
        if(StringUtils.isEmpty(sysUser.getId())){
            return ResultData.createFail("id不能为空");
        }

        if(file != null){
            //头像上传的根目录
            File uploadFile = new File(StringConstant.UPLOAD_ROOT_PATH);
            //头像名
            String fileName = StringUtil.getUUID()+ file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //图片上传的全路径
            String filePath = StringConstant.UPLOAD_ROOT_PATH+"\\"+fileName;
            //如果头像的路径在本地是否存在  如果不存在
            if(!uploadFile.exists()){
                //mkdirs()是创建多级目录
                uploadFile.mkdirs();
            }
            try {
                //并且将图片上传的全路径塞进去
                file.transferTo(new File(filePath));
            } catch (IOException e) {
                e.printStackTrace();
            }
            //将图片传入
            sysUser.setHeadImg(fileName);
        }
        //用户名不能修改
        sysUser.setUsername(null);
        SysUser curSysUser = getSysUserByToken(token).getData();
        sysUser.setUpdateTime(new Date());
        sysUser.setUpdateUserId(curSysUser.getId());

        log.info("修改系统用户:"+ JSON.toJSONString(sysUser));
        int i = sysUserMapper.updateSysUser(sysUser);
        if(i>0){
            return ResultData.createSuccess(null);
        }else{
            return ResultData.createFail("修改系统用户失败");
        }
    }


    /**
     * 删除系统用户
     *
     * @param sysUser
     * @return
     */
    @Transactional
    public ResultData delSysUser(SysUser sysUser) {
        if(StringUtils.isEmpty(sysUser.getId())){
            return ResultData.createFail("id不能为空");
        }
        sysUser.setDel(StringConstant.DEL_OK);
        log.info("删除系统用户:"+ JSON.toJSONString(sysUser));
        int i = sysUserMapper.delSysUser(sysUser);
        if(i>0){
            return ResultData.createSuccess(null);
        }else{
            return ResultData.createFail("删除系统用户失败");
        }
    }

    /**
     * 用户登录
     * @param sysUser
     * @return
     */
    public ResultData sysLogin(SysUser sysUser) {
        log.info("开始进行用户登录:"+JSON.toJSONString(sysUser));

        if(StringUtils.isEmpty(sysUser.getUsername())){
            return ResultData.createFail("用户名不能为空");
        }
        if(StringUtils.isEmpty(sysUser.getPassword())){
            return ResultData.createFail("密码不能为空");
        }
        sysUser.setDel(StringConstant.DEL_NO);
        SysUser loginSysUser = sysUserMapper.getSysUserByLogin(sysUser);
        if(loginSysUser !=null){
            //JSP -----> 用户信息放在session(session容易被攻击---->放弃)
            //token鉴权
            //1.如果我登录成功
            //2.生成一个token(token:字符串--->uuid)
            //3.一个token对应一个用户信息,放在一个全局的HashMap key:token字符串  value:用户信息
            //4.你获取用户信息,就需要你用登录成功时候token才行

            //登录成功
            //1.生成token字符串
            String token = StringUtil.getUUID();
            //2.一个token对应一个用户信息,放在一个全局的HashMap key:token字符串  value:用户信息
            redisUtil.set(token,JSON.toJSONString(loginSysUser));
            return ResultData.successData("登录成功",token);
        }else{
            return ResultData.createFail("用户名或密码错误,登录失败");
        }
    }

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    public ResultData<SysUser> getSysUserByToken(String token) {
        log.info("根据token获取用户信息:token===>"+token);
        SysUser sysUser = JSON.parseObject(redisUtil.get(token),SysUser.class);
        if(sysUser == null){
            return ResultData.createFail("token无效,请重新登录获取token");
        }
        return ResultData.successData("查询成功",sysUser);
    }




}
